package com.aaron.gesturehelper.gesturelib;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Set;

import com.aaron.gesturehelper.MyConfiguration;

import android.util.Log;

public class MyGestureLibrary {

	private static final String TAG = "MyGestureLibrary";
	private MyGestureStore mStore;
	private final File mPath;

	public static MyGestureLibrary fromFile(String path) {
		return fromFile(new File(path));
	}

	public static MyGestureLibrary fromFile(File file) {
		return new MyGestureLibrary(file);
	}

	private MyGestureLibrary(File path) {
		mPath = path;
		mStore = new MyGestureStore();
	}

	public MyInstanceLearner getLearner() {
		return mStore.getLearner();
	}

	public Set<String> getGestureEntries() {
		return mStore.getGestureEntries();
	}

	public ArrayList<MyPrediction> recognize(MyGesture gesture) {
		return mStore.recognize(gesture);
	}

	public void addGesture(String entryName, MyGesture gesture) {
		mStore.addGesture(entryName, gesture);
	}

	public void removeGesture(String entryName) {
		mStore.removeGesture(entryName);
	}

	public MyGesture getGestures(String entryName) {
		return mStore.getGestures(entryName);
	}

	public boolean save() {
		if (!mStore.hasChanged())
			return true;

		final File file = mPath;

		final File parentFile = file.getParentFile();
		if (!parentFile.exists()) {
			if (!parentFile.mkdirs()) {
				return false;
			}
		}

		boolean result = false;
		try {
			// noinspection ResultOfMethodCallIgnored
			file.createNewFile();
			mStore.save(new FileOutputStream(file), true);
			result = true;
		} catch (FileNotFoundException e) {
			if(MyConfiguration.DEBUG) {
				Log.d(TAG, "Could not save the gesture library in " + mPath, e);
			}
		} catch (IOException e) {
			if(MyConfiguration.DEBUG) {
				Log.d(TAG, "Could not save the gesture library in " + mPath, e);
			}
		}

		return result;
	}

	public boolean load() {
		boolean result = false;
		final File file = mPath;
		if (file.exists() && file.canRead()) {
			try {
				mStore.load(new FileInputStream(file), true);
				result = true;
			} catch (FileNotFoundException e) {
				if(MyConfiguration.DEBUG) {
					Log.d(TAG, "Could not load the gesture library from " + mPath,
						e);
				}
			} catch (IOException e) {
				if(MyConfiguration.DEBUG) {
					Log.d(TAG, "Could not load the gesture library from " + mPath,
						e);
				}
			}
		}

		return result;
	}
}
